//
//  BLEUtility.m
//
//  Created by Ole Andreas Torvmark on 9/22/12.
//  Copyright (c) 2012 Texas Instruments. All rights reserved.
//

#import "BLEUtility.h"
#import "AppDelegate.h"
@implementation BLEUtility
#define UUID_SERVICE  @"00001910-0000-1000-8000-00805f9b34fb"
#define UUID_READ  @"0000fff4-0000-1000-8000-00805f9b34fb"
#define UUID_WRITE  @"0000fff2-0000-1000-8000-00805f9b34fb"
#define UUID_HEART_RATE_MEASUREMENT  @"00002902-0000-1000-8000-00805f9b34fb"

+(void)printConnectedCnt
{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    
    for (int i=0; i<[myDelegate.peripheralArray count]; i++)
    {
        CBPeripheral *peripheral=[myDelegate.peripheralArray objectAtIndex:i];
        if (peripheral.isConnected) {
            NSLog(@"打印当前设备==>peripheral:%@  is connect!",peripheral.name);
        }else
        {
            NSLog(@"printConnectedCnt==> peripheral name is:%@, is not Connect",peripheral.name);
        }
    }
}
+(void)deleteBondPasswd
{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
      NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    
    NSLog(@"delete Bond Pass word---删除绑定信息...");
    for (int i=0; i<[myDelegate.peripheralArray count]; i++)
    {
        CBPeripheral *peripheral=[myDelegate.peripheralArray objectAtIndex:i];
        NSString *strKey=[NSString stringWithFormat:@"%@",CFUUIDCreateString(nil, peripheral.UUID)];
        [ud removeObjectForKey:strKey];
    }
    [ud synchronize];
}
+(void)writeBondPasswdData:(NSData *)data  p:(CBPeripheral *)p
{
    CBUUID *sUUID = [CBUUID UUIDWithString:UUID_SERVICE];
    CBUUID *cUUID = [CBUUID UUIDWithString:UUID_WRITE];
    
    for ( CBService *service in p.services )
    {
        if ([service.UUID isEqual:sUUID])
        {
            for ( CBCharacteristic *characteristic in service.characteristics )  //查找
            {
                if ([characteristic.UUID isEqual:cUUID])
                {
                    [p writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
                }
            }
        }
    }
}
+(void)writeData:(NSData *)data
{
    CBUUID *sUUID = [CBUUID UUIDWithString:UUID_SERVICE];
    CBUUID *cUUID = [CBUUID UUIDWithString:UUID_WRITE];
    
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    
     NSLog(@"peripheralArray的个数是:%lu",(unsigned long)[myDelegate.peripheralArray count]);
    for (int i=0; i<[myDelegate.peripheralArray count]; i++)
    {
        CBPeripheral *peripheral=[myDelegate.peripheralArray objectAtIndex:i];
      
        if (peripheral.isConnected) {
            NSLog(@"send data to peripheral:%@",peripheral.name);
        }else
        {
           NSLog(@"peripheral name is:%@, is not Connect",peripheral.name);
        }
        
        for ( CBService *service in peripheral.services )
        {
            if ([service.UUID isEqual:sUUID])
            {
                for ( CBCharacteristic *characteristic in service.characteristics )  //查找
                {
                    if ([characteristic.UUID isEqual:cUUID])
                    {
                        NSLog(@"data length is 30*1000sleep:%d",(int)data.length);
                        [peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
                        
                        break;
                    }
                }
            }
        }
//        usleep(80*1000);
    }
    
}
+(void)writeCharacteristic:(CBPeripheral *)peripheral sUUID:(NSString *)sUUID cUUID:(NSString *)cUUID data:(NSData *)data {
    // Sends data to BLE peripheral to process HID and send EHIF command to PC
    for ( CBService *service in peripheral.services ) {
        if ([service.UUID isEqual:[CBUUID UUIDWithString:sUUID]]) {
            for ( CBCharacteristic *characteristic in service.characteristics ) {
                if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:cUUID]]) {
                    /* EVERYTHING IS FOUND, WRITE characteristic ! */
                    [peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
                    
                }
            }
        }
    }
}

+(void)writeCharacteristic:(CBPeripheral *)peripheral sCBUUID:(CBUUID *)sCBUUID cCBUUID:(CBUUID *)cCBUUID data:(NSData *)data {
    // Sends data to BLE peripheral to process HID and send EHIF command to PC
    for ( CBService *service in peripheral.services ) {
        if ([service.UUID isEqual:sCBUUID]) {
            for ( CBCharacteristic *characteristic in service.characteristics ) {
                if ([characteristic.UUID isEqual:cCBUUID]) {
                    /* EVERYTHING IS FOUND, WRITE characteristic ! */
                    [peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
                    
                }
            }
        }
    }
}


+(void)readCharacteristic:(CBPeripheral *)peripheral sUUID:(NSString *)sUUID cUUID:(NSString *)cUUID {
    for ( CBService *service in peripheral.services ) {
        if([service.UUID isEqual:[CBUUID UUIDWithString:sUUID]]) {
            for ( CBCharacteristic *characteristic in service.characteristics ) {
                if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:cUUID]]) {
                    /* Everything is found, read characteristic ! */
                    [peripheral readValueForCharacteristic:characteristic];
                }
            }
        }
    }
}

+(void)readCharacteristic:(CBPeripheral *)peripheral sCBUUID:(CBUUID *)sCBUUID cCBUUID:(CBUUID *)cCBUUID {
    for ( CBService *service in peripheral.services ) {
        if([service.UUID isEqual:sCBUUID]) {
            for ( CBCharacteristic *characteristic in service.characteristics ) {
                if ([characteristic.UUID isEqual:cCBUUID]) {
                    /* Everything is found, read characteristic ! */
                    [peripheral readValueForCharacteristic:characteristic];
                }
            }
        }
    }
}

+(void)setNotificationForCharacteristic:(CBPeripheral *)peripheral sUUID:(NSString *)sUUID cUUID:(NSString *)cUUID enable:(BOOL)enable {
    for ( CBService *service in peripheral.services ) {
        if ([service.UUID isEqual:[CBUUID UUIDWithString:sUUID]]) {
            for (CBCharacteristic *characteristic in service.characteristics ) {
                if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:cUUID]])
                {
                    /* Everything is found, set notification ! */
                    [peripheral setNotifyValue:enable forCharacteristic:characteristic];
                }
                
            }
        }
    }
}
/*
 这个方法一定要在查找到Characteristic这一步之后才可以调用,在didDiscoverCharacteristicsForService里面或之后调用才可以.android是直接把
 services和Characteristic一起找到.ios是一级一级的查找.
 */
+(void)enAbleReadCharacteristic:(CBPeripheral *)peripheral
{
    CBUUID *sUUID = [CBUUID UUIDWithString:UUID_SERVICE];
    CBUUID *cUUID = [CBUUID UUIDWithString:UUID_READ];

    for ( CBService *service in peripheral.services )
    {
        if ([service.UUID isEqual:sUUID])
        {
            for (CBCharacteristic *characteristic in service.characteristics )
            {
                if ([characteristic.UUID isEqual:cUUID])
                {
                    [peripheral setNotifyValue:YES forCharacteristic:characteristic];
                }
            }
        }
    }
}
+(void)disEnableReadDataCharacteristic:(CBPeripheral *)peripheral
{
    CBUUID *sUUID = [CBUUID UUIDWithString:UUID_SERVICE];
    CBUUID *cUUID = [CBUUID UUIDWithString:UUID_READ];
    
    for ( CBService *service in peripheral.services )
    {
        if ([service.UUID isEqual:sUUID])
        {
            for (CBCharacteristic *characteristic in service.characteristics )
            {
                if ([characteristic.UUID isEqual:cUUID])
                {
                    [peripheral setNotifyValue:NO forCharacteristic:characteristic];
                }
                
            }
        }
    }
}
+(void)setNotificationForCharacteristic:(CBPeripheral *)peripheral sCBUUID:(CBUUID *)sCBUUID cCBUUID:(CBUUID *)cCBUUID enable:(BOOL)enable {
    for ( CBService *service in peripheral.services ) {
        if ([service.UUID isEqual:sCBUUID]) {
            for (CBCharacteristic *characteristic in service.characteristics ) {
                if ([characteristic.UUID isEqual:cCBUUID])
                {
                    /* Everything is found, set notification ! */
                    [peripheral setNotifyValue:enable forCharacteristic:characteristic];
                    
                }
                
            }
        }
    }
}


+(bool) isCharacteristicNotifiable:(CBPeripheral *)peripheral sCBUUID:(CBUUID *)sCBUUID cCBUUID:(CBUUID *) cCBUUID {
    for ( CBService *service in peripheral.services ) {
        if ([service.UUID isEqual:sCBUUID]) {
            for (CBCharacteristic *characteristic in service.characteristics ) {
                if ([characteristic.UUID isEqual:cCBUUID])
                {
                    if (characteristic.properties & CBCharacteristicPropertyNotify) return YES;
                    else return NO;
                }
                
            }
        }
    }
    return NO;
}


+(CBUUID *) expandToTIUUID:(CBUUID *)sourceUUID {
    CBUUID *expandedUUID = [CBUUID UUIDWithString:TI_BASE_LONG_UUID];
    unsigned char expandedUUIDBytes[16];
    unsigned char sourceUUIDBytes[2];
    [expandedUUID.data getBytes:expandedUUIDBytes];
    [sourceUUID.data getBytes:sourceUUIDBytes];
    expandedUUIDBytes[2] = sourceUUIDBytes[0];
    expandedUUIDBytes[3] = sourceUUIDBytes[1];
    expandedUUID = [CBUUID UUIDWithData:[NSData dataWithBytes:expandedUUIDBytes length:16]];
    return expandedUUID;
}


+(NSString *) CBUUIDToString:(CBUUID *)inUUID {
    unsigned char i[16];
    [inUUID.data getBytes:i];
    if (inUUID.data.length == 2) {
        return [NSString stringWithFormat:@"%02hhx%02hhx",i[0],i[1]];
    }
    else {
        uint32_t g1 = ((i[0] << 24) | (i[1] << 16) | (i[2] << 8) | i[3]);
        uint16_t g2 = ((i[4] << 8) | (i[5]));
        uint16_t g3 = ((i[6] << 8) | (i[7]));
        uint16_t g4 = ((i[8] << 8) | (i[9]));
        uint16_t g5 = ((i[10] << 8) | (i[11]));
        uint32_t g6 = ((i[12] << 24) | (i[13] << 16) | (i[14] << 8) | i[15]);
        return [NSString stringWithFormat:@"%08x-%04hx-%04hx-%04hx-%04hx%08x",g1,g2,g3,g4,g5,g6];
    }
    return nil;
}

@end
